package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportServer;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class ReportServerImpl implements ReportServer {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计接口
     * @return
     * */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //统计begin到end的天数
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
           begin= begin.plusDays(1);
          dateList.add(begin);
        }
        //获得TurnoverReportVO中的dateList
        String date="";
        for (LocalDate localDate : dateList) {
            if(!localDate.equals(end)){
                date=date + localDate+",";
            }else {
                date = date + localDate;
            }
        }
        //查询营业额
        //select sum(amount) from orders where order_time > ? and order_time < ? and status = 5;
        List<Double> turnoverList=new ArrayList<>();
        //遍历天数，查询每天营业额
        for (LocalDate localDate : dateList) {
            //将begin，end类型转化为LocalDateTime类型
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            //获取每天的营业额
           Double turnover= orderMapper.sumByMap(map);
           if(turnover==null){
               turnover=0.0;
           }
            turnoverList.add(turnover);
        }
        return  TurnoverReportVO.builder()
                .dateList(date)
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     * */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //获取日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //获取用户总量
        //SQL：select count(id) from user where create_time < ?
        List<Integer> totalUserList=new ArrayList<>();
        //获取新增用户数量
        //SQL: select count(id) from user where create_time > ? and create_time < ?
        List<Integer> newUserList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //将localDate格式改为LocalDateTime
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MAX);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map =new HashMap();
            map.put("end",endTime);
          Integer totalUser=userMapper.countByMap(map);
          //添加到用户总量中
          totalUserList.add(totalUser);
          map.put("begin",beginTime);
          Integer newUser=userMapper.countByMap(map);
          //添加到新增用户中
          newUserList.add(newUser);
        }
        //封装结果数据
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     * */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //定义一个变量初始化begin，后面统计总订单
        LocalDate beginTime1=begin;
        //1.获取日期
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //2.获取每日订单数
        List<String> orderCountList=new ArrayList<>();
        //3.获取每日订单有效数
        List<String> validOrderCountList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //格式化日期
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //SQL:select count(number) from orders where order_time > ? and order_time < ? and status = 5
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            //获取每日订单数
            String orderNumber=orderMapper.getOrderList(map);
            orderCountList.add(orderNumber);
            //获取每日订单有效数
            map.put("status",Orders.COMPLETED);
          String validOrderNumber=orderMapper.getOrderList(map);
          validOrderCountList.add(validOrderNumber);
        }
        //4.获取订单总数
        //5.获取有效订单总数
        LocalDateTime beginTime = LocalDateTime.of(beginTime1, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map=new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        //获取订单总数
        Integer totalOrderCount=Integer.valueOf(orderMapper.getOrderList(map));
        //获取订单有效数
        map.put("status",Orders.COMPLETED);
        Integer validOrderCount=Integer.valueOf(orderMapper.getOrderList(map));
        //6.获取订单完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
            orderCompletionRate= validOrderCount.doubleValue()/totalOrderCount;
        }

        //封装结果
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量排名top10接口
     * @param begin
     * @param end
     * @return
     * */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //SQL:select od.name,sum(od.number) from order_detail od, orders o
        // where od.order_id = o.id and o.order_time > ? and o.order_time < ?
        // and o.status = 5
        // group by od.name order by sum(od.number) desc limit 10
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.getTop10(beginTime, endTime);
        //封装结果
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOS) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }
        log.info("nameList:{}",nameList);
        log.info("numberList:{}",numberList);
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出Excel报表接口
     * @param response
     * */
    public void export(HttpServletResponse response) {
        LocalDate now = LocalDate.now();
        LocalDate beginDate = now.minusDays(30);
        LocalDate endDate = now.minusDays(1);
        //从数据库中获取数据
        BusinessDataVO dataVO = workspaceService.getBusinessData(LocalDateTime.of
                (beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //2.通过POI将数据写入到Excel文件中
        try {
            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);
            //获取sheet
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据-时间
            sheet.getRow(1).getCell(1).setCellValue("时间"+beginDate + "至" + endDate);
            //获得第四行
             XSSFRow row3 = sheet.getRow(3);
             row3.getCell(2).setCellValue(dataVO.getTurnover());
             row3.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
             row3.getCell(6).setCellValue(dataVO.getNewUsers());
             //获得第五行
             XSSFRow row4 = sheet.getRow(4);
             row4.getCell(2).setCellValue(dataVO.getValidOrderCount());
             row4.getCell(4).setCellValue(dataVO.getUnitPrice());
             //获得明细数据
             for (int i = 0; i < 30; i++) {
                 LocalDate date = beginDate.plusDays(i);
                 //获取每日的营业额
                 BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of
                         (date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                 sheet.getRow(7 + i).getCell(1).setCellValue(date.toString());
                 sheet.getRow(7 + i).getCell(2).setCellValue(businessData.getTurnover());
                 sheet.getRow(7 + i).getCell(3).setCellValue(businessData.getValidOrderCount());
                 sheet.getRow(7 + i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                 sheet.getRow(7 + i).getCell(5).setCellValue(businessData.getUnitPrice());
                 sheet.getRow(7 + i).getCell(6).setCellValue(businessData.getNewUsers());
             }
             //通过输出流将excel文件下载到客户端浏览器
             ServletOutputStream outputStream = response.getOutputStream();
             excel.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
